package com.xinyue.cross.server.client;

import com.xinyue.game.message.GameServerMessageModel;
import com.xinyue.game.message.GameServerRequestHeader;
import com.xinyue.game.message.GameServerResponseHeader;
import com.xinyue.game.utils.GameServerUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

public class ServerMessageHandler extends ChannelInboundHandlerAdapter {
    private static Logger logger = LoggerFactory.getLogger(ServerMessageHandler.class);
    private ApplicationContext context;
    private static final String HEART_BEAT_URI = "clientHeartbeat";

    public ServerMessageHandler(ApplicationContext context) {
        this.context = context;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("与业务服务连接创建成功，channelId: {}", GameServerUtil.getChannelId(ctx.channel()));
        ctx.fireChannelActive();
        // 连接成功之后，发送一个心跳
        this.sendHeartbeat(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        this.sendHeartbeat(ctx);
        ctx.fireUserEventTriggered(evt);
    }

    private void sendHeartbeat(ChannelHandlerContext ctx) {
        XinyueCrossClientConfig config = context.getBean(XinyueCrossClientConfig.class);
        GameServerRequestHeader requestHeader = new GameServerRequestHeader();
        requestHeader.setClientInstanceId(config.getClientInstanceId());
        requestHeader.setRequestTime(System.currentTimeMillis());
        requestHeader.setRequestId(GameServerUtil.getUuid());
        requestHeader.setUserKey(config.getClientInstanceId());
        requestHeader.setRequestUri(HEART_BEAT_URI);
        requestHeader.setClientIp(GameServerUtil.getLocalAddress());
        GameServerMessageModel<GameServerRequestHeader> messageModel = new GameServerMessageModel<>();
        messageModel.setHeader(requestHeader);
        ctx.writeAndFlush(messageModel);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("与服务器连接断开,channelId: {}", GameServerUtil.getChannelId(ctx.channel()));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        IGameServerMessageHandler gameServerMessageHandler = context.getBean(IGameServerMessageHandler.class);
        GameServerMessageModel<GameServerResponseHeader> messageModel = (GameServerMessageModel<GameServerResponseHeader>) msg;
        if (messageModel.getHeader().getRequestUri().equals(HEART_BEAT_URI)) {
            // 返回的心跳消息，不处理
            logger.debug("心跳返回，不处理，header: {}", messageModel.getHeader());
        } else {
            gameServerMessageHandler.handlerMessage(messageModel, ctx);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("客户端异常", cause);
    }
}
